import { ref, computed } from 'vue';
import { Cell } from '../type';

export function selectedModule(getData: () => Cell[], emit: Function) {
  const selectedItems = ref<number[]>([]);

  // 计算是否全选
  const isAllSelected = computed(() => {
    const data = getData();
    if (data.length === 0) return false;

    // 过滤出可选择的行（isCheckbox不为false的行）
    const selectableRows = data.filter((item) => item.isCheckbox !== false);
    return selectableRows.length > 0 && selectedItems.value.length === selectableRows.length;
  });

  // 计算是否部分选择
  const isIndeterminate = computed(() => {
    return selectedItems.value.length > 0 && !isAllSelected.value;
  });

  // 全选/取消全选
  const handleSelectAll = (event: Event) => {
    const target = event.target as HTMLInputElement;
    const data = getData();

    if (target.checked) {
      // 只选择可选择的行
      selectedItems.value = data.map((_, index) => index).filter((index) => data[index].isCheckbox !== false);
    } else {
      selectedItems.value = [];
    }

    emit(
      'selection-change',
      selectedItems.value.map((i) => data[i])
    );
  };

  // 选择单行
  const handleSelectRow = (rowIndex: number) => {
    const data = getData();
    // 检查该行是否可选择
    if (data[rowIndex].isCheckbox === false) {
      return;
    }

    const index = selectedItems.value.indexOf(rowIndex);
    if (index > -1) {
      selectedItems.value.splice(index, 1);
    } else {
      selectedItems.value.push(rowIndex);
    }

    emit(
      'selection-change',
      selectedItems.value.map((i) => data[i])
    );
  };

  // 清空选择
  const clearSelection = () => {
    selectedItems.value = [];
    emit('selection-change', []);
  };

  // 选择指定行
  const selectRows = (rowIndices: number[]) => {
    const data = getData();
    selectedItems.value = rowIndices.filter((index) => index >= 0 && index < data.length && data[index].isCheckbox !== false);

    emit(
      'selection-change',
      selectedItems.value.map((i) => data[i])
    );
  };

  return {
    selectedItems,
    isAllSelected,
    isIndeterminate,
    handleSelectAll,
    handleSelectRow,
    clearSelection,
    selectRows
  };
}
